﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;
using System.Diagnostics;
using System.Web;
using Microsoft.SharePoint.Utilities;

namespace Liebrand.UrlShortener
{
    public static class FarmHelper
    {

        #region Methods

        public static void Activate()
        {
            Trace.WriteLine("Activating FarmFeature");

            var admin = SPAdministrationWebApplication.Local;

            using (var site = admin.Sites[0])
            {
                using (var web = site.RootWeb)
                {
                    var storageName = SPUtility.GetLocalizedString("$Resources:liebrandurlshortener,StorageName", "liebrandurlshortener", web.Language);
                    var storageUrl = SPUtility.GetLocalizedString("$Resources:liebrandurlshortener,StorageUrl", "liebrandurlshortener", web.Language);
                    var storageDescription = SPUtility.GetLocalizedString("$Resources:liebrandurlshortener,StorageDescription", "liebrandurlshortener", web.Language);

                    Trace.WriteLine("Checking if list exists.");
                    if (web.ListExists(storageName))
                    {
                        Trace.WriteLine("Deleting List");
                        var list = web.Lists[storageName];

                        list.Delete();
                        web.Update();
                    }

                    if (!web.ListExists(storageName))
                    {
                        Trace.WriteLine("Creating List");

                        var listId = web.Lists.Add(storageUrl, storageDescription, SPListTemplateType.GenericList);

                        var list = web.Lists[listId];
                        list.Title = storageName;

                        list.EnableAttachments = false;
                        list.AddField("RedirectTo", "", SPFieldType.Note, true);

                        var view = list.DefaultView;
                        view.ViewFields.Add("RedirectTo");
                        view.Update();

                        list.Update();
                    }
                }
            }

            Trace.WriteLine("Done.");

        }

        public static void Deactivate()
        {
        }
        #endregion

    }
}
